package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;

    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //添加套餐表单基本信息
        setmealDao.add(setmeal);
        //得到新增套餐的id
        Integer setmealId = setmeal.getId();
        if(checkgroupIds != null && checkgroupIds.length > 0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String , Integer> map = new HashMap<String, Integer>();
                map.put("setmealId" , setmealId);
                map.put("checkgroupId" , checkgroupId);
                setmealDao.setCheckgroupAndSetmeal(map);
            }
        }
        //得到添加到数据库的照片名称
        String fileName = setmeal.getImg();
        //添加到redis库中，然后根据差值删除垃圾照片
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES , fileName);
        //生成静态页面（包括套餐列表和套餐详情页面）
        getFindFileNameAndHtmlName();
    }

    private void getFindFileNameAndHtmlName() {
        List<Setmeal> list = setmealDao.getFindAllSetmeal();
        //生成套餐列表页面
        getMobileSetmeal(list);

        //生成套餐详情页面
        getMobileSetmealDetail(list);
    }

    //生成套餐列表页面，查询出的所有的套餐基本信息
    private void getMobileSetmeal(List<Setmeal> list) {
        Map map = new HashMap();
        map.put("setmealList" , list);
        freemarkerHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //生成套餐列表详情页面，调用dao层的根据id查询套餐方法
    private void getMobileSetmealDetail(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal" , setmealDao.findById(setmeal.getId()));
            freemarkerHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }



    }

    //通用格式。生成通用的html静态页面，filename模板名称，htmlname生成的静态页面
    public void freemarkerHtml(String fileName , String htmlName , Map map){
        try {
            Configuration configuration = freeMarkerConfigurer.getConfiguration();
            Template template = configuration.getTemplate(fileName);
            Writer out = new FileWriter(new File(outPutPath + "/" + htmlName));
            template.process(map , out);
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    //分页查询
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage , pageSize);
        String queryString = queryPageBean.getQueryString();
        Page<Setmeal> page = setmealDao.findPage(queryString);
        long total = page.getTotal();
        List<Setmeal> rows = page.getResult();
        return new PageResult(total , rows);
    }

    //查询全部的套餐集合，在手机页面展示
    public List<Setmeal> getFindAllSetmeal() {
        List<Setmeal> setmeal = setmealDao.getFindAllSetmeal();
        return setmeal;
    }

    //根据id查看套餐详情（包括检查组的信息以及对应的检查项的信息）
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealDao.findById(id);
        return setmeal;
    }

    //根据id删除套餐数据
    public void deleteById(int id) {
        setmealDao.deleteById(id);
    }

    public List<Map> findSetmealByNameAndCount() {
        return setmealDao.findSetmealByCount();
    }




}
